<script setup lang="ts">
import { addPostionAPI, delPostionAPI, getPostionMenuAPI, getRoleDetailAPI, setRolePostionAPI, updatePostionAPI, } from '@/apis/role';
import { useLayoutStore } from '@/stores/modules/setting';
import { MenuList, MenuResponseData, records, roleData, roleDataRes, } from '@/types/role';
import dayjs from 'dayjs';
import { onMounted, ref } from 'vue'

const page = ref(1)
const limit = ref(5)
const roleList = ref<records>([])
const total = ref(0)
const dialogVisible = ref(false)
const form = ref()
const roleName = ref('')

//搜索
const search = () => {
    getRoleData()
    roleName.value = ''
}
//重置
const layoutStore = useLayoutStore()
const reset = () => {
    layoutStore.refresh = !layoutStore.refresh
}
//改变当前页
const changeCurrent = (currentPage: number) => {
    page.value=currentPage
    getRoleData()
}
//改变当前页码大小
const changePageSize = (pageSize: number) => {
    limit.value=pageSize
    getRoleData()
    page.value-1
}

//获取用户列表
const getRoleData = async () => {
    const res: roleDataRes = await getRoleDetailAPI(page.value, limit.value, roleName.value)
    console.log(res);
    roleList.value = res.data.records
    total.value = res.data.total
}
onMounted(() => {
    getRoleData()
})
//定义表单数据
const roleForm = ref<roleData>({
    createTime: dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss'),
    updateTime: dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss'),
    roleName: '',
    remark: null,
})
//定义规则
// 校验规则
const checkRoleName = (_rule: any, value: any, callback: any) => {
    if (value.length >= 2) {
        callback()
    } else {
        callback(new Error('职位名称至少两位'))
    }
}
const rules = {
    roleName: [
        { required: true, message: '用户密码不能为空', trigger: "blur" },
        { validator: checkRoleName, trigger: 'blur' }
    ]
}

//添加用户
const addPostion = () => {
    roleForm.value.id = undefined
    roleForm.value.roleName = ''
    dialogVisible.value = true
}

//编辑用户
const updatePostion = (row: any) => {
    dialogVisible.value = true
    Object.assign(roleForm.value, row)
}

// 删除用户
const onConfirm = async (id: number) => {
    await delPostionAPI(id)
    if (roleList.value.length > 1) {
        ElMessage.success('删除成功')
        getRoleData()
    } else {
        page.value - 1
        ElMessage.success('删除成功')
        getRoleData()
    }
}
//取消按钮
const cancel = () => {
    form.value.resetFields()
    dialogVisible.value = false
}

//确认按钮
const confirm = async () => {
    await form.value.validate()
    if (!roleForm.value.id) {
        await addPostionAPI(roleForm.value)
        ElMessage.success('添加成功')
    } else {
        await updatePostionAPI(roleForm.value)
        ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getRoleData()
    form.value.resetFields()
}
//分配权限
const drawer = ref(false)
const menuList = ref<MenuList>([])
const selectArr = ref<number[]>([])
const defaultProps = {
    children: 'children',
    label: 'name',
}
const setAcl = async (row: roleData) => {
    drawer.value = true
    Object.assign(roleForm.value, row)
    const res: MenuResponseData = await getPostionMenuAPI(roleForm.value.id as number)
    menuList.value = res.data    
    selectArr.value = filterSelectArr(menuList.value, [])
}
const filterSelectArr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        if(item.select && item.level==4){
            initArr.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr)
        }  
    })
    return initArr
}

//确定按钮
const tree=ref()
const handler = async() => {
    const roleId=roleForm.value.id
    const arr=tree.value.getCheckedKeys()
    const arr1=tree.value.getHalfCheckedKeys()
    const permissionId=arr.concat(arr1)
    await setRolePostionAPI(roleId as number,permissionId)
    drawer.value=false
    ElMessage.success('分配权限成功')
    getRoleData()

}
</script>

<template>
    <!-- 头部 -->
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="职位搜索:">
                <el-input placeholder="请输入搜索职位的关键字" v-model="roleName"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="roleName ? false : true" @click="search">搜索</el-button>
                <el-button type="primary" plain @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <!-- 主体 -->
    <el-card style="margin: 10px 0px;">
        <!-- 按钮 -->
        <el-button type="primary" @click="addPostion">添加职位</el-button>
        <!-- 表格 -->
        <el-table border style="margin: 10px 0px;" :data="roleList">
            <el-table-column type="index" label="#" align="center"></el-table-column>
            <el-table-column prop="id" label="ID" align="center"></el-table-column>
            <el-table-column prop="roleName" label="职位名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row }">
                    <el-button type="primary" icon="User" style="width: 100px;" size="small"
                        @click="setAcl(row)">分配权限</el-button>
                    <el-button type="primary" icon="Edit" size="small" @click="updatePostion(row)">编辑</el-button>
                    <el-popconfirm :title="`你确认要删除${row.roleName}吗?`" confirm-button-text="确认"
                        cancel-button-text="取消" @confirm="onConfirm(row.id)" width="260px">
                        <template #reference>
                            <el-button type="primary" icon="Delete" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[1, 3, 5, 10]"
            :background="true" layout="prev, pager, next, jumper,->, sizes,total" :total="total"
            @current-change="changeCurrent" @size-change="changePageSize" />
        <!-- 角色弹框-->
        <el-dialog :title="roleForm.id ? '编辑职位' : '添加职位'" v-model="dialogVisible">
            <!-- 表单组件 -->
            <el-form ref="form" :model="roleForm" :rules="rules">
                <el-form-item label="职位名称" prop="roleName" style="margin-top: 20px;">
                    <el-input placeholder="请你输入职位名称" v-model="roleForm.roleName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">确定</el-button>
            </template>
        </el-dialog>
        <!-- 权限树 -->
        <!-- 抽屉组件:分配职位的菜单权限与按钮的权限 -->
        <el-drawer v-model="drawer">
            <template #header>
                <h4>分配菜单与按钮的权限</h4>
            </template>
            <template #default>
                <!-- 树形控件 -->
                <el-tree ref="tree" :data="menuList" show-checkbox node-key="id" default-expand-all
                    :default-checked-keys="selectArr" :props="defaultProps" />
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer = false">取消</el-button>
                    <el-button type="primary" @click="handler">确定</el-button>
                </div>
            </template>
        </el-drawer>
    </el-card>
</template>

<style scoped lang="scss">
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>